package cn.lonecloud.dao.impl;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.lonecloud.dao.UserDao;
import cn.lonecloud.model.User;
import cn.lonecloud.util.DBUtils;

/**
 * 用户dao实现层
 * @author lonecloud
 */
public class UserDaoImpl implements UserDao {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5985159082400084603L;

	private String tableName = "t_user";

	@Override
	public User save(User entity) {
		String sql = "insert into " + tableName + "(name,loginName,password,sex,registerTime,address,tel)"
				+ "values(?,?,?,?,?,?,?)";
		DBUtils.execute(sql, entity.getName(), entity.getLoginName(), entity.getPassword(), entity.getSex(), new Date(),
				entity.getAddress(), entity.getTel());
		return entity;
	}

	@Override
	public void update(User entity) {
		String sql = "UPDATE " + tableName
				+ "set name=?,loginName=?,password=?,sex=?,registerTime=?,address=?,tel=? where id=?";
		DBUtils.execute(sql, entity.getName(), entity.getLoginName(), entity.getPassword(), entity.getSex(), new Date(),
				entity.getAddress(), entity.getTel(), entity.getId());
	}

	@Override
	public void deleteById(int id) {
		String sql = "delete from " + tableName + "where id=?";
		DBUtils.execute(sql, id);
	}

	@Override
	public User findById(int id) {
		String sql = "select id,name,loginName,password,sex,registerTime,address,tel from " + tableName + "where id=?";
		ResultSet resultSet = DBUtils.Query(sql, id);
		return transferObj(resultSet);
	}

	@Override
	public List<User> findAll() {
		List<User> users = new ArrayList<>();
		String sql = "select id,name,loginName,password,sex,registerTime,address,tel from " + tableName;
		ResultSet resultSet = DBUtils.Query(sql);
		User user = null;
		while (true) {
			user = this.transferObj(resultSet);
			if (user != null) {
				users.add(user);
			} else {
				break;
			}
		}
		return users;
	}

	private User transferObj(ResultSet resultSet) {
		User user = null;
		try {
			if (resultSet != null && resultSet.next()) {
				user = new User();
				user.setId(resultSet.getInt("id"));
				user.setName(resultSet.getString("name"));
				user.setLoginName(resultSet.getString("loginName"));
				user.setPassword(resultSet.getString("password"));
				user.setSex(resultSet.getString("sex"));
				user.setRegisterTime(resultSet.getDate("registerTime"));
				user.setAddress(resultSet.getString("address"));
				user.setTel(resultSet.getString("tel"));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}

	@Override
	public User getUserByNameAndPwd(String username, String password) {
		ResultSet resultSet = DBUtils.Query("select * from " + tableName + " where loginName= ? and password= ?",
				username, password);
		if (resultSet != null) {
			User user = this.transferObj(resultSet);
			return user;
		}
		return null;
	}
}
